package football.haha.com.footballtv.view;


import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.Toast;

import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcUtil;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaList;
import org.videolan.libvlc.NativeCrashHandler;

import java.lang.ref.WeakReference;

public class VideoView extends SurfaceView implements SurfaceHolder.Callback, IVideoPlayer {

    public VideoView(Context context, String videoURL) {
        super(context);
        this.init(context, videoURL);
    }

    public VideoView(Context context, AttributeSet attrs, String videoURL) {
        super(context, attrs);
        this.init(context, videoURL);
    }

    public VideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context, videoURL);
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public VideoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.init(context, videoURL);
    }


    public static final String TAG = VideoView.class.getSimpleName();

    private String videoURL;
    private SurfaceHolder holder;
    public LibVLC libvlc;
    private final static int VideoSizeChanged = 999;
    private Context context;
    private EventHandler mEventHandler;

    private Handler handler = new MyHandler(this);

    private class MyHandler extends Handler {

        private WeakReference<VideoView> mOwner;

        public MyHandler(VideoView owner) {
            mOwner = new WeakReference<VideoView>(owner);
        }

        @Override
        public void handleMessage(Message msg) {
            final VideoView videoView = mOwner.get();
            if (videoView == null) {
                return;
            }

            // SamplePlayer events
            if (msg.what == VideoSizeChanged) {
                videoView.setSize(msg.arg1, msg.arg2);
                return;
            }
//            PrintUtil.print(VideoView.class,"time="+libvlc.getTime());

            // Libvlc events
            Bundle b = msg.getData();
            int event = b.getInt("event");
            //265 卡住
            //8194 0... 3 0 260(应该是缓冲完成) 274(开始播放图像) 265（已经开始播放之后卡住或流中断或网络中断） 266（无法播放） 268(正在播放) 267(正在播放)
//            PrintUtil.print(VideoView.class, "9999999999999999,event=" + event);
            switch (event) {
                case 274://开始播放图像
                    break;
                case 265://已经开始播放之后卡住或流中断或网络中断 MediaPlayerEndReached
                case 262://MediaPlayerStopped（包含执行了stop操作）
                case 266://无法播放

                    break;

            }

/**            switch (event) {
 case EventHandler.MediaPlayerEndReached://265
 //                    PrintUtil.print(VideoView.class,"999999999999999event=MediaPlayerEndReached");
 videoView.releasePlayer();
 break;
 case EventHandler.MediaPlayerPlaying://260
 //                    PrintUtil.print(VideoView.class,"9999999999999999event=MediaPlayerPlaying");
 break;
 case EventHandler.MediaPlayerPaused:
 //                    PrintUtil.print(VideoView.class,"999999999999999event=MediaPlayerPaused");
 break;
 case EventHandler.MediaPlayerStopped://262
 //                    PrintUtil.print(VideoView.class,"9999999999999999event=MediaPlayerStopped");
 break;
 }*/
        }
    }

    public void setVideoURL(String videoURL) {
        this.videoURL = videoURL;
    }


    private void init(Context context, String videoURL) {
        this.context = context;
        this.videoURL = videoURL;


        holder = getHolder();
        holder.setFormat(PixelFormat.TRANSLUCENT);
        holder.addCallback(this);

        //屏蔽其触摸
        setFocusable(false);
        setFocusableInTouchMode(false);


    }


    public void createPlayer(String videoURL) {
        releasePlayer();
        try {
            // Create a new media player
            libvlc = new LibVLC();
            mEventHandler = libvlc.getEventHandler();
            libvlc.init(context);
            libvlc.setHardwareAcceleration(LibVLC.HW_ACCELERATION_DISABLED);
            libvlc.setSubtitlesEncoding("");
            libvlc.setAout(LibVLC.AOUT_OPENSLES);
            libvlc.setTimeStretching(false);
            libvlc.setVerboseMode(false);
            libvlc.setNetworkCaching(2500);
            NativeCrashHandler.getInstance().setOnNativeCrashListener(nativecrashListener);

            if (LibVlcUtil.isGingerbreadOrLater())
                libvlc.setVout(LibVLC.VOUT_ANDROID_WINDOW);
            else
                libvlc.setVout(LibVLC.VOUT_ANDROID_SURFACE);

            libvlc.setHttpReconnect(true);
            LibVLC.restartInstance(context);
            mEventHandler.addHandler(handler);
            holder.setKeepScreenOn(true);
            MediaList list = libvlc.getMediaList();
            list.clear();
//            list.add(new Media(libvlc, LibVLC.PathToURI(videoURL)), false, false, true);
            list.add(new Media(libvlc, LibVLC.PathToURI(videoURL)));
            libvlc.playIndex(0);
            libvlc.closeAout();
            libvlc.setVolume(0);
            if (libvlc != null)
                libvlc.attachSurface(holder.getSurface(), this);

        } catch (Exception e) {
            Log.e(TAG, e.toString());
            Toast.makeText(context, "Error creating player!", Toast.LENGTH_LONG).show();
        }


    }


    public void releasePlayer() {
        if (libvlc == null)
            return;
        mEventHandler.removeHandler(handler);
        libvlc.stop();
        libvlc.detachSurface();
        libvlc.closeAout();
        libvlc.destroy();
        libvlc = null;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        createPlayer(videoURL);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releasePlayer();

    }


    public NativeCrashHandler.OnNativeCrashListener nativecrashListener = new NativeCrashHandler.OnNativeCrashListener() {

        @Override
        public void onNativeCrash() {
        }

    };


    private void setSize(int width, int height) {
//        if (libvlc != null) {
//            libvlc.closeAout();
//            libvlc.setVolume(0);
//        }
        int surfaceFrameW = getMeasuredWidth();
        int surfaceFrameH = getMeasuredHeight();
        if (surfaceFrameW * surfaceFrameW <= 1)
            return;
        // force surface buffer size
        if (holder != null) {
            holder.setFixedSize(surfaceFrameW, surfaceFrameH);
        } else {
            Toast.makeText(context, "Holder was null!!!", Toast.LENGTH_SHORT).show();
        }
        // set display size
        ViewGroup.LayoutParams lp = getLayoutParams();
        lp.width = surfaceFrameW;
        lp.height = surfaceFrameH;
        setLayoutParams(lp);
        invalidate();
    }

    /**
     * 改变view的大小
     *
     * @param width
     * @param height
     */
    public void changeSize(int width, int height) {
        ViewGroup.LayoutParams lp = getLayoutParams();
        lp.width = width;
        lp.height = height;
        holder.setFixedSize(lp.width, lp.height);
        setLayoutParams(lp);
        invalidate();
    }


    @Override
    public void eventHardwareAccelerationError() {
        Log.e(TAG, "Error with hardware acceleration");
        releasePlayer();
        Toast.makeText(context, "Error with hardware acceleration",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void setSurfaceLayout(int width, int height, int visible_width,
                                 int visible_height, int sar_num, int sar_den) {
        Message msg = Message.obtain(handler, VideoSizeChanged, width,
                height);
        msg.sendToTarget();
    }

    // Used only for old stuff
    @Override
    public int configureSurface(Surface surface, int width, int height,
                                int hal) {
        if (LibVlcUtil.isICSOrLater() || surface == null)
            return -1;
        if (width * height == 0)
            return 0;
        if (hal != 0)
            holder.setFormat(hal);
        holder.setFixedSize(width, height);
        return 1;
    }

    public void play() {
        if (libvlc != null) {
            libvlc.play();
        } else {
            createPlayer(videoURL);
        }
    }

    public void pause() {
        if (libvlc != null) {
            libvlc.pause();
        }
    }


}
